package cn.caplike.demo.nio._2021.buffer;

import cn.caplike.demo.nio._2021.channel.NioFromIo;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Objects;

/**
 * KeyWords: 零拷贝, 直接内存.
 *
 * @author LiKe
 * @version 1.0.0
 * @date 2022-01-17 13:05
 */
@SuppressWarnings("DuplicatedCode")
public class DirectByteBufferDemo {

    public static void main(String[] args) throws Throwable {
        FileInputStream inputStream = new FileInputStream(Objects.requireNonNull(NioFromIo.class.getResource("/data/nio-from-io-read.txt")).getPath());
        FileOutputStream outputStream = new FileOutputStream(Objects.requireNonNull(NioFromIo.class.getResource("/data/nio-from-io-write.txt")).getPath());

        final FileChannel inputChannel = inputStream.getChannel();
        final FileChannel outputChannel = outputStream.getChannel();

        // 直接字节缓冲
        ByteBuffer buffer = ByteBuffer.allocateDirect(1024); // 堆外内存 (直接内存) -> 零拷贝

        while (true) {
            buffer.clear();
            // 实际读到的字节个数
            int read = inputChannel.read(buffer);
            System.out.println("read: " + read);
            if (-1 == read) {
                break;
            }

            buffer.flip();
            outputChannel.write(buffer);
        }

        inputChannel.close();
        outputChannel.close();
    }

}
